package com.sky.service.admin.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.mapper.admin.DishMapper;
import com.sky.pojo.Dish;
import com.sky.result.PageResult;
import com.sky.service.admin.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;

    @Override
    @Transactional
    public void addDish(DishDTO dishDTO) {
        Dish dish = new Dish();
        dish.setName(dishDTO.getName());
        dish.setCategoryId(dishDTO.getCategoryId());
        dish.setPrice(dishDTO.getPrice());
        dish.setImage(dishDTO.getImage());
        dish.setDescription(dishDTO.getDescription());
        dish.setStatus(dishDTO.getStatus());
        dish.setMakeTime(dishDTO.getMakeTime());
        dishMapper.addDish(dish);
        Long id = dish.getId();
        if (dishDTO.getFlavors() != null && dishDTO.getFlavors().size() > 0) {
            dishDTO.getFlavors().forEach(Flavor -> Flavor.setDishId(id));
            dishMapper.addDishFlavor(dishDTO.getFlavors());
        }
    }

    @Override
    public PageResult findByPage(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(),dishPageQueryDTO.getPageSize());
        List<DishVO> byPage = dishMapper.findByPage(dishPageQueryDTO.getName(), dishPageQueryDTO.getCategoryId(), dishPageQueryDTO.getStatus());
        Page<DishVO> voPage=(Page<DishVO>) byPage;
        return new PageResult(voPage.getTotal(),voPage.getResult());
    }

    @Override
    public void delete(List<Integer> ids) {
        dishMapper.delete(ids);
    }

    @Override
    public DishVO findById(Integer dishId) {
        return dishMapper.findById(dishId);
    }

    @Override
    public void update(DishVO dishVO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishVO,dish);
        dishMapper.update(dish);
        if (dishVO.getFlavors() != null && dishVO.getFlavors().size() > 0) {
            dishVO.getFlavors().forEach(Flavor -> Flavor.setDishId(dish.getId()));
            dishMapper.deleteDishFlavor(dish.getId());
            dishMapper.addDishFlavor(dishVO.getFlavors());
        }
    }
}
